module("mymqtt", package.seeall);

m = mqtt.Client("clientid", 120, "MichaelHu", "3735026") 

function mqttInit(IP, MqttID)
    local t = tmr.create()
    t:register(500, tmr.ALARM_AUTO, function()
         --m:publish("/topic", "hello", 0, 0, function(client) print("sent") end)
    end)
    
    m:on("connect", function(client) 
        t:start()
        --print ("connected") 
        -- Calling subscribe/publish only makes sense once the connection
        -- was successfully established. You can do that either here in the
        -- 'connect' callback or you need to otherwise make sure the
        -- connection was established (e.g. tracking connection status or in
        -- m:on("connect", function)).
        
        -- subscribe topic with qos = 0
        client:subscribe("/topic/" .. node.chipid(), 0, function(client) 
            print("/topic/" .. node.chipid() .. "  subscribe success") 
            end)
            
        -- publish a message with data = hello, QoS = 0, retain = 0
        client:publish("/topic", "订阅ID /topic/" .. node.chipid(), 0, 0, function(client) 
        print("sent") 
        end)
    end)
    
    m:on("offline", function(conn)
        print("disconnect to broker...")
        print(node.heap())
    end)
    
    m:connect(IP, 1883, 0) 
end

